package com.shwread.android.qysw.activity.task;

import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.NewActionHelp;
import com.ciko.code.base.BaseActicity;
import com.ciko.code.utils.NetWorkUtils;
import com.ciko.code.utils.PerferencesUtil;
import com.google.gson.ExclusionStrategy;
import com.google.gson.FieldAttributes;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.shwread.android.qysw.QyReaderApp;
import com.shwread.android.qysw.bean.que.OptionBean;
import com.shwread.android.qysw.bean.que.QueDetailedBean;
import com.shwread.android.qysw.bean.que.QueInfo;
import com.shwread.android.qysw10000241.R;
import com.shwread.android.ui.dialog.NetworkDialog;
import com.shwread.android.ui.widget.QuePopupWindow;
import com.shwread.http.base.ObjectHttpResponseHandler;
import com.shwread.http.base.TextHttpResponseHandler;

import org.apache.http.Header;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import logic.util.ScreenUtil;
import logic.util.Util;
import logic.util.Utils;

/**
 * 问卷详情
 */
public class QuestionnaireDetailActivity extends BaseActicity
        implements QuePopupWindow.PopItemListener, View.OnLayoutChangeListener {
    /**
     * 问卷名
     */
    private TextView tvQueName;
    /**
     * 副标题
     */
    private TextView tvQueSubItem;
    /**
     * 上一题
     */
    private Button btnPreviousQue;
    /**
     * 目录
     */
    private Button btnQueCatalog;
    /**
     * 下一题
     */
    private Button btnNextQue;
    private ViewPager vpQue;
    /**
     * 导航栏
     */
    private LinearLayout llNavigation;
    /**
     * 根布局
     */
    private LinearLayout llRootView;
    private int queId;
    /**
     * 问卷调查是否已完成
     */
    private boolean isFinish = true;

    /**
     * 问卷答案列表
     */
    public static ArrayList<OptionBean> QueList = new ArrayList<>();
    /**
     * 问卷题目列表
     */
    private List<QueInfo> list;
    /**
     * 当前位置
     */
    private int index;
    private QueDetailedBean.QuestInfoBean questInfoBean;
    private PerferencesUtil perferencesUtil;

    @Override
    protected void initTopBar() {
        setTitle("问卷详情");
        enableNavLeftImg();
    }

    @Override
    protected void initLayout() {
        setContentView(R.layout.activity_questionnaire_detail);
        setResult(1000, getIntent());
    }

    @Override
    protected void initView() {
        vpQue = findViewByID(R.id.vp_que);
        tvQueName = findViewByID(R.id.tv_que_name);
        tvQueSubItem = findViewByID(R.id.tv_que_sub_item);
        btnPreviousQue = findViewByID(R.id.btn_previous_que);
        btnQueCatalog = findViewByID(R.id.btn_que_catalog);
        btnNextQue = findViewByID(R.id.btn_next_que);
        llNavigation = findViewByID(R.id.ll_navigation);
        llRootView = findViewByID(R.id.ll_root_view);
    }

    @Override
    protected void initAdapter() {
    }

    @Override
    protected void initDates() {
        if (!NetWorkUtils.isConnected(this)) {
            new NetworkDialog(this).show();
            return;
        }
        QueList.clear();
        perferencesUtil = PerferencesUtil.getInstance(this);
        queId = getIntent().getIntExtra("queId", -1);
        long lastTime = perferencesUtil.getQueLastTimeStamp(queId);
        NewActionHelp.intoQuestionnaire(this, queId, lastTime, new ObjectHttpResponseHandler<QueDetailedBean>() {
            @Override
            public void onFailure(int i, Header[] headers, String s, Throwable throwable) {
                Log.e("sss", "失败--" + s);
                Utils.showToast(QyReaderApp.application, "加载失败");
            }

            @Override
            public void onSuccess(int i, Header[] headers, QueDetailedBean queDetailedBean, String s) {
                Log.e("sss", "成功--" + s);
                perferencesUtil.setQueLastTimeStamp(queDetailedBean.getRequestTime(), queId);
                questInfoBean = queDetailedBean.getQuestInfo();
                if (queDetailedBean.getIsModify()) {//判断题是否有改变
                    perferencesUtil.setQueBean("", questInfoBean.getId());//题目发生改变删除以前保存的答案
                    Utils.showToast(QyReaderApp.application, "题库发生改变,已保存的答案被清除");
                }
                tvQueName.setText(questInfoBean.getTitle());
                tvQueSubItem.setText(questInfoBean.getIntroduction());
                isFinish = questInfoBean.getQuestionnaireUserInfo().getIsFinish();
                list = questInfoBean.getQuestionnaireItemInfos();
                initOptionList();
                vpQue.setAdapter(fpAdapter);
                if (list.size() == 1) {
                    btnNextQue.setBackgroundResource(R.drawable.img_que_submit);
                }
            }

            @Override
            public Type getType() {
                return new TypeToken<QueDetailedBean>() {
                }.getType();
            }
        });
    }

    /**
     * 初始化答案列表
     */
    private void initOptionList() {
        OptionBean queItemBean;
        if (isFinish) {//已完成问卷
            List<QueInfo.OptionSelectedInfosBean> optionList;
            for (QueInfo queInfo : list) {
                queItemBean = new OptionBean()
                        .setItemId(queInfo.getId())
                        .setItemType(queInfo.getItemType())
                        .setFinish(true);
                optionList = queInfo.getOptionSelectedInfos();
                switch (queInfo.getItemType()) {
                    case "1":
                        queItemBean.setOptionId(String.valueOf(optionList.get(0).getOptionId()));
                        break;
                    case "2"://多选
                        String itemId = "";
                        for (QueInfo.OptionSelectedInfosBean bean : optionList) {
                            itemId += String.format("%s,", bean.getOptionId());
                        }
                        if (!TextUtils.isEmpty(itemId)) {
                            queItemBean.setOptionId(itemId.substring(0, itemId.length() - 1));
                        }
                        break;
                    case "3":
                        queItemBean.setOptionId(String.valueOf(optionList.get(0).getOptionId()));
                        break;
                    case "4":
                        queItemBean.setAnswerContent(optionList.get(0).getAnswer_content());
                        break;
                    case "5":
                        queItemBean.setFileType(String.valueOf(optionList.get(0).getFile_type()))
                                .setAnswerContent(optionList.get(0).getAnswer_content());
                        break;
                }
                QueList.add(queItemBean);
            }
        } else {
            String json = perferencesUtil.getQueBean(questInfoBean.getId());
            if (!TextUtils.isEmpty(json)) {
                ArrayList<OptionBean> optionBeanArrayList = new Gson().fromJson(json, new TypeToken<ArrayList<OptionBean>>() {
                }.getType());
                if (optionBeanArrayList != null && optionBeanArrayList.size() != 0) {//有本地缓存数据
                    QueList = optionBeanArrayList;
                    return;
                }
            }
            for (QueInfo queInfo : list) {
                QueList.add(new OptionBean()
                        .setItemId(queInfo.getId())
                        .setItemType(queInfo.getItemType()));
            }
        }
    }

    @Override
    protected void initListener() {
        btnPreviousQue.setOnClickListener(this);
        btnQueCatalog.setOnClickListener(this);
        btnNextQue.setOnClickListener(this);
        llRootView.addOnLayoutChangeListener(this);
        //viewpager滑动监听
        vpQue.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {//滑动监听
                index = position;
                if (position + 1 == fpAdapter.getCount()) {
                    btnNextQue.setBackgroundResource(R.drawable.img_que_submit);
                } else {
                    btnNextQue.setVisibility(View.VISIBLE);
                    btnNextQue.setBackgroundResource(R.drawable.img_que_next);
                }
                //隐藏键盘
                hideKeyboard();
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    /**
     * 隐藏键盘
     */
    private void hideKeyboard() {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(), 0);
    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {
            case R.id.btn_previous_que://上一页
                if (vpQue.getCurrentItem() > 0) {
                    vpQue.setCurrentItem(vpQue.getCurrentItem() - 1, true);
                } else {
                    Utils.showToast(this, "已经是第一题了");
                }
                break;
            case R.id.btn_que_catalog://目录
                new QuePopupWindow(this).showPopupWindow(index, QueList, this);
                break;
            case R.id.btn_next_que:
                if (vpQue.getCurrentItem() < fpAdapter.getCount() - 1) {//下一题
                    vpQue.setCurrentItem(vpQue.getCurrentItem() + 1, true);
                } else {//提交
                    if (isFinish) {
                        Util.showToast(this,"该问卷已经提交过了");
                        return;
                    }
                    for (int i = 0; i < QueList.size(); i++) {
                        if (!QueList.get(i).isFinish()) {
                            Util.showToast(QyReaderApp.application, "请答完所有题再进行提交");
                            vpQue.setCurrentItem(i, false);
                            return;
                        }
                    }
                    btnNextQue.setEnabled(false);
                    Gson gson = new GsonBuilder()
                            .setExclusionStrategies(new ExclusionStrategy() {

                                @Override
                                public boolean shouldSkipField(FieldAttributes fa) {
                                    return "isFinish".equals(fa.getName());
                                }

                                @Override
                                public boolean shouldSkipClass(Class<?> clazz) {
                                    return false;
                                }
                            })
                            .create();
                    String json = gson.toJson(QueList);
                    NewActionHelp.finishQuestionnaire(this, queId, json, new TextHttpResponseHandler() {
                        @Override
                        public void onFailure(int i, Header[] headers, String s, Throwable throwable) {
                            Log.e("sss", "失败--" + s);
                            Util.showToast(QyReaderApp.application, "提交失败");
                            btnNextQue.setEnabled(true);
                        }

                        @Override
                        public void onSuccess(int i, Header[] headers, String s) {
                            Log.e("sss", "成功--" + s);
                            Util.showToast(QyReaderApp.application, "提交成功");
                            QuestionnaireDetailActivity.this.setResult(1000, getIntent());
                            finish();
                        }
                    });
                }
                break;
        }
    }

    private FragmentPagerAdapter fpAdapter = new FragmentPagerAdapter(getSupportFragmentManager()) {
        @Override
        public Fragment getItem(int position) {
            return QuestionItemFragment.newInstance(position, isFinish, list.get(position));
        }

        @Override
        public int getCount() {
            return list.size();
        }
    };

    @Override
    public void click(int position) {
        vpQue.setCurrentItem(position, false);
    }


    @Override
    public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
        //通过根布局大小变化监听键盘弹出收起
        if (oldBottom != 0 && bottom != 0 && (oldBottom - bottom > ScreenUtil.screenHeight / 3)) {
            llNavigation.setVisibility(View.GONE);
            //通过隐藏和显示解决底部导航栏空白bug
            tvQueName.setVisibility(View.GONE);
            tvQueName.setVisibility(View.VISIBLE);
        } else if (oldBottom != 0 && bottom != 0 && (bottom - oldBottom > ScreenUtil.screenHeight / 3)) {
            llNavigation.setVisibility(View.VISIBLE);
        }
    }

    @Override
    protected void onDestroy() {
        if (questInfoBean != null) {
            perferencesUtil.setQueBean(new Gson().toJson(QueList), questInfoBean.getId());
        }
        NewActionHelp.cancel(this);
        super.onDestroy();
    }
}